package labox.innovation.gameserver.model;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javolution.util.FastMap;
import labox.innovation.config.Config;
import labox.innovation.gameserver.model.actor.instance.FuzePcInstance;

/**
 * @author ljsh
 * @date 2010-4-12
 * @version 1.0
 * @description 管理所有离线玩家
 */
public class L2PartyManager {
	private static final Logger _log = LoggerFactory.getLogger(PartyMemberExDropped.class);
	private static L2PartyManager instance = new L2PartyManager();
	/**
	 * 保存所有离线的玩家，
	 */
	private static FastMap<Long, PartyMemberExDropped> _allOfflinePlayer = new FastMap<Long, PartyMemberExDropped>();

	private L2PartyManager() {
	}

	public static L2PartyManager getInstance() {
		return instance;
	}

	public Map<Long, PartyMemberExDropped> getAllOfflinePlayer() {
		return _allOfflinePlayer;
	}

	public static void addOfflineMember(PartyMemberExDropped member) {
		_allOfflinePlayer.put(member.getCharacter(), member);
	}

	/**
	 * @param obj
	 * @param date
	 *            检测是否离线超过10分钟，超过则队伍中删除 ,世界中删除，_allOfflinePlayer中删除
	 */
	public void checkTimeOut(PartyMemberExDropped obj, long date) {
		if (obj != null && obj.getParty() != null) {
			if (_log.isDebugEnabled())
				_log.debug("检测组队状态下离线的玩家 ：" + obj.getCharacter() + " 队伍 ：" + obj.getParty());
			long playerid = obj.getCharacter();
			if (date - obj.getDropTime() >= Config.LOGOUTSPACETIME) {
				L2Party p = obj.getParty();
				if (p != null) {
					p.removePartyMember(obj.getParty().getPlayerById(playerid));
				}
				_allOfflinePlayer.remove(playerid);
			} else {
				FuzePcInstance newplayer = FuzeWorld.getInstance().getPlayer(playerid);
				if (newplayer != null) {
					obj.getParty().removePartyMember(obj.getParty().getPlayerById(playerid));
					obj.cancel();
					//当队伍存在，但队伍人数还有成员时则加入队伍
					if (obj.getParty() != null&&obj.getParty().getMemberCount()>0) {
						newplayer.joinParty(obj.getParty());
					}
					_allOfflinePlayer.remove(playerid);
				}
			}
		}

	}

	/**
	 * @param player
	 *            当玩家离线时，调用该方法：该方法维护在组队情况下离线
	 */
	public static void addPartyMemberExDropped(FuzePcInstance player) {
		if (player.getParty() != null) {
			PartyMemberExDropped _temp = new PartyMemberExDropped(player.getParty(), player);
			addOfflineMember(_temp);
		}

	}

	/**
	 * @param player
	 *            角色上线时调用，检查是否存在在组队情况下离队
	 */
	public void checkTimeOut(FuzePcInstance player) {
		PartyMemberExDropped drop = _allOfflinePlayer.get(player.getObjectId());
		if (drop != null) {
			checkTimeOut(drop, System.currentTimeMillis());
		}

	}
}
